package org.six11.olive3.server;

import java.io.PrintWriter;
import java.util.Map;

import org.six11.olive3.net.Message;
import org.six11.olive3.net.MessageHandler;
import org.six11.olive3.net.MessageNames;
import org.six11.olive3.picturephone.server.MessageQueue;
import org.six11.olive3.picturephone.server.ServerStateConstants;
import org.six11.olive3.util.MiscFunctions;
import org.six11.olive3.util.MultiState;
import org.six11.util2.Debug;

public class DownloadMessageHandler extends MessageHandler {

  private OliveRuntimeData data;
  private MultiState programState;

  public DownloadMessageHandler(OliveRuntimeData data, MultiState programState) {
    this.data = data;
    this.programState = programState;
  }

  public void handleNow(Message m, PrintWriter out) {
    String uid = m.getParamValue(MessageNames.PARAM_USER_ID);
    // TODO: the oliveruntimedata way of storing messages should still be used, but it should be
    // rolled in to the MessageQueue class. The whole routing strategy needs to change, so each user
    // only has a private queue. If a particular message must be broadcast to multiple users, that
    // message should be copied and put into each user queue.

    // data.retrieveData(uid,
    // MiscFunctions.safeInt(m.getParamValue(MessageNames.PARAM_MESSAGE_INDEX)), out);
    Map<String, MessageQueue> queues = (Map<String, MessageQueue>) programState
        .getValue(ServerStateConstants.MESSAGE_QUEUES);
    if (queues.containsKey(uid)) {
      queues.get(uid).flush(out, true);
    } else {
      bug("Hmm, there is no message queue for user " + uid
          + ". I'll make one.");
      queues.put(uid, new MessageQueue(uid));
    }
  }

}
